package com.example.zhuwenjing

import Student
import android.app.Activity
import android.content.Intent
import android.os.Bundle
import android.widget.Button
import androidx.activity.result.contract.ActivityResultContracts
import androidx.appcompat.app.AppCompatActivity
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.google.gson.Gson
import com.google.gson.reflect.TypeToken
import java.io.File

class MainActivity : AppCompatActivity() {
    private lateinit var recyclerView: RecyclerView
    private lateinit var adapter: StudentAdapter
    private val students = mutableListOf<Student>()
    private val gson = Gson()
    private val fileName = "students.json"

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)

        recyclerView = findViewById(R.id.recyclerView)
        recyclerView.layoutManager = LinearLayoutManager(this)
        adapter = StudentAdapter(students)
        recyclerView.adapter = adapter

        loadStudents()

        val button = findViewById<Button>(R.id.button)
        button.setOnClickListener {
            val intent = Intent(this, MainActivity2::class.java)
            addStudentLauncher.launch(intent)
        }
    }

    private val addStudentLauncher = registerForActivityResult(ActivityResultContracts.StartActivityForResult()) { result ->
        if (result.resultCode == Activity.RESULT_OK) {
            val newStudents = result.data?.getParcelableArrayListExtra<Student>("newStudents")
            newStudents?.let {
                students.addAll(it)
                adapter.notifyDataSetChanged()
                saveStudents()
            }
        }
    }

    private fun loadStudents() {
        val file = File(filesDir, fileName)
        if (file.exists()) {
            val json = file.readText()
            val type = object : TypeToken<List<Student>>() {}.type
            val loadedStudents: List<Student> = gson.fromJson(json, type)
            students.addAll(loadedStudents)
            adapter.notifyDataSetChanged()
        }
    }

    private fun saveStudents() {
        val json = gson.toJson(students)
        val file = File(filesDir, fileName)
        file.writeText(json)
    }
}